﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace DownLoadFtpFile
{
    public class FtpHelper
    {
        public string Host { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }

        public FtpHelper(string host, string userName, string password)
        {
            if (!host.EndsWith("/"))
            {
                Host = host + "/";
            }
            else
            {
                Host = host;
            }
            UserName = userName;
            Password = password;
        }

        public List<FtpDirectoryEntry> ListDirectory()
        {
            FtpWebResponse response = null;
            Stream stream = null;
            StreamReader streamReader = null;
            try
            {
                var request = GetRequest(String.Empty);
                request.Method = WebRequestMethods.Ftp.ListDirectory;
                response = request.GetResponse() as FtpWebResponse;
                if (response == null)
                {
                    return null;
                }
                stream = response.GetResponseStream();
                if (stream == null)
                {
                    return null;
                }
                streamReader = new StreamReader(stream);
                var content = streamReader.ReadToEnd();
                var lines = content.Split('\n');
                var entries = new List<FtpDirectoryEntry>();
                foreach (var line in lines)
                {
                    try
                    {
                        if (string.IsNullOrWhiteSpace(line))
                        {
                            continue;
                        }

                        var entry = CreateFtpDirectoryEntry(line);
                        entries.Add(entry);
                    }
                    catch (Exception e)
                    {
                        Logger.Log.WriteEntry(string.Format("获取文件创建时间时出错:错误信息:{0}", e.ToString()));
                        continue;
                    }
                }
                return entries;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
                if (stream != null)
                {
                    stream.Close();
                }
                if (streamReader != null)
                {
                    streamReader.Close();
                }
            }
        }

        public void DownloadFiles(string path, params string[] files)
        {
            FileStream outstream = null;
            FtpWebResponse response = null;
            Stream instream = null;
            foreach (var file in files)
            {
                var request = GetRequest(file);
                try
                {
                    request.Method = WebRequestMethods.Ftp.DownloadFile;
                    request.UseBinary = true;
                    outstream = new FileStream(Path.Combine(path, file), FileMode.Create);
                    response = (FtpWebResponse) request.GetResponse();
                    instream = response.GetResponseStream();
                    if (instream != null)
                    {
                        var buffLength = 16384;
                        var buffer = new byte[buffLength];
                        var bytesRead = instream.Read(buffer, 0, buffLength);
                        while (bytesRead > 0)
                        {
                            outstream.Write(buffer, 0, bytesRead);
                            bytesRead = instream.Read(buffer, 0, buffLength);
                        }
                        Logger.Log.WriteEntry(string.Format("下载文件:{0}完成", request.RequestUri));
                    }
                }
                catch (Exception e)
                {
                    Logger.Log.WriteEntry(string.Format("下载文件:{0}出错！错误信息:{1}", request.RequestUri, e.ToString()));
                }

                finally
                {
                    if (outstream != null)
                    {
                        outstream.Close();
                    }
                    if (response != null)
                    {
                        response.Close();
                    }
                    if (instream != null)
                    {
                        instream.Close();
                    }
                }
            }
        }


        public FtpWebRequest GetRequest(string fileName)
        {
            var url = Host;
            if (!string.IsNullOrWhiteSpace(fileName))
            {
                url += fileName;
            }
            FtpWebRequest request = (FtpWebRequest) WebRequest.Create(url);
            request.Credentials = new NetworkCredential(UserName, Password);
            return request;
        }

        private FtpDirectoryEntry CreateFtpDirectoryEntry(string name)
        {
            name = name.TrimEnd('\r');
            var entry = new FtpDirectoryEntry {Name = name};
            var request = GetRequest(name);
            request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
            using (var response = (FtpWebResponse) request.GetResponse())
            {
                entry.CreateTime = response.LastModified;
            }
            return entry;
        }
    }
}